<template>
  <div>
    <el-dialog
      :title="$t('m.AUTHENTICATION_MANAGEMENT')"
      :modal="false"
      :visible.sync="authDialog"
      center
      :close-on-click-modal="false"
      custom-class="auth-dialog"
      :before-close="handleClose"
    >
      <el-container>
        <el-aside width="200px">
          <div class="aside">
            <div class="main-part">{{$t('m.AUTHENTICATION_GROUP')}}</div>
            <el-tabs
              tab-position="left"
              v-model="currentTabName"
              type="card"
              @tab-click="handleClick"
              style="height: 100%;width:100%"
            >
              <el-tab-pane
                v-for="(item,index) in authList"
                :key="index"
                :name="item.rightGroupID"
                :label="item.rightGroupName"
              ></el-tab-pane>
            </el-tabs>
          </div>
        </el-aside>
        <el-main>
          <div class="_main">
            <div>
              {{$t('m.AUTHENTICATION_GROUP_NAME')}}：
              <span
                v-if="currentItem.editStatus == 'get'"
              >{{currentItem.rightGroupName}}</span>
              <span v-else>
                <el-input style="width:50%" v-model="modelName" ref="modelName"></el-input>
                <span v-show="showTips" style="color:red">请输入权限组名称</span>
              </span>
            </div>
            <div class="_main-header">
              <div
                :class="titleNum == 1?'header-part checked':'header-part'"
                @click="handleGoto('1')"
              >{{$t('m.ASSOCIATED_MODULE')}}</div>
              <div
                :class="titleNum == 2?'header-part checked':'header-part'"
                @click="handleGoto('2')"
              >{{$t('m.ASSOCIATED_GROUP')}}</div>
              <div
                :class="titleNum == 3?'header-part checked':'header-part'"
                @click="handleGoto('3')"
              >{{$t('m.ASSOCIATED_VIDEO')}}</div>
            </div>
            <div class="_main-body">
              <el-scrollbar class="default-scrollbar" wrap-class="default-scrollbar__wrap">
                <!-- 权限树 -->
                <el-tree
                  v-show="titleNum == 1"
                  :data="authTreeDataShow"
                  icon-class="el-icon-arrow-right"
                  node-key="rightID"
                  highlight-current
                  :default-expanded-keys="expandedTreeKey"
                  ref="authTree"
                  :filter-node-method="groupFilter"
                  @check-change="handleCheckChange('auth')"
                  show-checkbox
                >
                  <span slot-scope="{ node }">
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
                <!-- 关联组树 -->
                <el-tree
                  v-show="titleNum == 2"
                  :data="userGroupTreeData"
                  icon-class="el-icon-arrow-right"
                  node-key="id"
                  highlight-current
                  :default-expanded-keys="expandedTreeKey"
                  ref="groupTree"
                  :filter-node-method="groupFilter"
                  @check-change="handleCheckChange('group')"
                  show-checkbox
                ></el-tree>
                <!-- 关联视频树 -->
                <el-tree
                  v-show="titleNum == 3"
                  :data="videoGroupTreeData"
                  icon-class="el-icon-arrow-right"
                  node-key="id"
                  highlight-current
                  :default-expanded-keys="expandedTreeKey"
                  ref="videoTree"
                  :filter-node-method="groupFilter"
                  @check-change="handleCheckChange('video')"
                  show-checkbox
                ></el-tree>
              </el-scrollbar>
            </div>
          </div>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <div>
          <el-button @click="handleAdd" style="float:left" size="small">{{$t('m.ADD')}}</el-button>
          <el-button
            @click="currentItem.editStatus == 'add' ||currentItem.editStatus == 'update' ?handleCancel():handleDel()"
            style="float:right"
            size="small"
          >{{currentItem.editStatus == 'add' ||currentItem.editStatus == 'update' ?$t('m.CANCEL'):$t('m.DELECT')}}</el-button>
          <el-button
            @click="currentItem.editStatus == 'add'||currentItem.editStatus == 'update'?handleCreate():handleUpdate()"
            style="float:right"
            size="small"
          >{{currentItem.editStatus == 'add'||currentItem.editStatus == 'update'?$t('m.CONFIRM'):$t('m.EDIT')}}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
// import { authData } from '@/utils/test'
import { toTree } from '@/utils/util'
import { rightgroup, rightmodule, rightgrouprelation } from '@/api/dataManage'
import { dataflow } from '@/api/data'
import deepClone from '@/utils/clone'
export default {
  components: {},
  props: {
    authDialog: Boolean,
    source: Object,
  },
  data() {
    return {
      titleNum: '1',
      expandedTreeKey: [], //默认展开调度组节点key
      authList: [],
      currentTab: {},
      authTreeData: [],
      authTreeDataShow: [],
      modelName: '',
      editStatus: 'get',
      currentTabName: '',
      authTreeCheckedArr: [], //权限组织树选中的权限 rightID
      groupTreeCheckedArr: [],
      videoTreeCheckedArr: [],
      showTips: false,
      currentItem: {},
    }
  },
  computed: {
    ...mapGetters({
      userGroupTreeData: 'userGroupTreeData',
      videoGroupTreeData: 'videoGroupTreeData',
    }),
    currentStatus() {
      if (this.currentItem) return this.currentItem.editStatus
    },
  },

  watch: {
    modelName() {
      if (this.modelName != '') {
        this.showTips = false
      }
    },
    currentStatus() {
      this.fiterUserGroupTreeData()
    },
  },
  methods: {
    init() {
      let _this = this
      this.getQueryRightModule()
      rightgroup({
        event: 'QueryRightGroup',
      }).then((res) => {
        let authList = res.data.eventdata
        _this.authList = authList.filter((e) => {
          return e.isAdmin == 0
        })
        rightgrouprelation({
          event: 'QueryRightGroupRelation',
        }).then((result) => {
          let list = result.data.eventdata
          let checkedArr = []
          _this.authList.forEach((e) => {
            e.editStatus = 'get'
            list.forEach((g) => {
              if (e.rightGroupID == g.rightGroupID) {
                e.group = g.group
              }
            })
          })
          if (_this.authList.length > 0) {
            let data = this.authList[0]
            _this.currentItem = data
            _this.currentTabName = data.rightGroupID
            data.name = data.rightGroupID
            _this.handleClick(data)
          }
          _this.fiterUserGroupTreeData()
        })
      })
    },
    eventMore(e) {
      let _this = this
      console.log(e)
      switch (e.type) {
        case 'RightGroupAdd':
          if (e.result == 'succ') {
            this.handleUpdateRelation(e.rightGroupID)
          } else {
            this.$message.error('权限组新增失败')
          }
          break
        case 'RightGroupMod':
          if (e.result == 'succ') {
            this.handleUpdateRelation(e.rightGroupID)
          } else {
            if (e.reason == '132:right group is use') {
              this.$message.error('该权限组正在使用中，不可修改')
              return
            }
            this.$message.error('权限组修改失败')
          }
          break
        case 'RightGroupDel':
          if (e.result == 'succ') {
            this.init()
          } else {
            this.$message.error('权限组删除失败')
          }
          break
        case 'RightGroupSet':
          break
        default:
          break
      }
    },
    // 对数据进行过滤
    fiterUserGroupTreeData() {
      if (!this.currentItem) {
        return
      }
      if (this.currentItem.editStatus == 'get') {
        this.$nextTick(() => {
          this.recursion(this.videoGroupTreeData, true)
          this.recursion(this.userGroupTreeData, true)
          this.recursion(this.authTreeDataShow, true)
        })
      } else {
        this.$nextTick(() => {
          this.recursion(this.videoGroupTreeData, false)
          this.recursion(this.userGroupTreeData, false)
          this.recursion(this.authTreeDataShow, false)
        })
      }
      this.$forceUpdate()
    },
    //递归
    recursion(data, bool) {
      // 对数据进行过滤
      const convert = (arr) => {
        arr.forEach((item) => (item.disabled = bool))
        return arr.map((item) => {
          if (item.children) {
            item.children = convert(item.children)
          }
          return item
        })
      }
      return convert(data)
    },
    //4.7.12.6	查询功能模块
    getQueryRightModule() {
      let obj = {
        event: 'QueryRightModule',
      }
      rightmodule(obj).then((res) => {
        this.authTreeData = res.data.eventdata
      })
    },
    //标签切换
    handleClick(tab, event) {
      let _this = this
      this.currentTab = tab
      this.currentItem = this.authList.filter((e) => {
        return tab.name == e.rightGroupID
      })[0]
      if (this.currentItem.editStatus != 'add') {
        this.currentItem.editStatus = 'get'
      }
      let obj = {
        event: 'QueryRightGroup',
        rightGroupID: tab.name,
      }
      this.handleGoto('1')
      //完整树 listAuth
      let listAuth = deepClone(this.authTreeData)
      //权限树
      let rightIDArr = this.currentItem.rightID
      listAuth.forEach((element) => {
        element.isCheck = false
        this.currentItem.editStatus == 'get'
          ? (element.disabled = true)
          : (element.disabled = false)
      })
      this.handleMakeTree(listAuth)
      this.$nextTick(() => {
        _this.$refs.authTree.setCheckedKeys(rightIDArr)
      })
    },
    //关联切换
    handleGoto(num) {
      this.titleNum = num
      let checkedArr = []
      let group = this.currentItem.group
      if (num == 2) {
        group.forEach((g) => {
          if (g.groupType == 'organ' || g.groupType == 'dispatchgroup')
            checkedArr.push(g.groupID)
        })
        this.$nextTick(() => {
          this.$refs.groupTree.setCheckedKeys(checkedArr)
        })
      } else if (num == 3) {
        group.forEach((g) => {
          if (g.groupType == 'videogroup') checkedArr.push(g.groupID)
        })
        this.$nextTick(() => {
          this.$refs.videoTree.setCheckedKeys(checkedArr)
        })
      }
    },
    //组织树点击
    handleCheckChange(type) {
      let arr = []
      let checkedNodesAll
      if (type == 'auth') {
        checkedNodesAll = this.$refs.authTree.getCheckedNodes()
        if (
          checkedNodesAll == null ||
          checkedNodesAll == undefined ||
          checkedNodesAll == ''
        ) {
          return
        }
        checkedNodesAll.forEach((e) => {
          arr.push(e.rightID)
        })
        this.authTreeCheckedArr = arr
        this.currentItem.rightID = deepClone(arr)
      } else if (type == 'group') {
        checkedNodesAll = this.$refs.groupTree.getCheckedNodes()
        if (
          checkedNodesAll == null ||
          checkedNodesAll == undefined ||
          checkedNodesAll == ''
        ) {
          return
        }
        checkedNodesAll.forEach((e) => {
          // arr.push({ groupType: e.obj.groupType, groupID: e.id })
          arr.push({ groupType: 'organ', groupID: e.id })
        })
        this.groupTreeCheckedArr = arr
        let group = this.currentItem.group
        let newGroup = group.filter((e) => {
          return e.groupType != 'organ' && e.groupType != 'dispatchgroup'
        })
        newGroup = newGroup.concat(arr)
        this.currentItem.group = deepClone(newGroup)
      } else if (type == 'video') {
        checkedNodesAll = this.$refs.videoTree.getCheckedNodes()
        if (
          checkedNodesAll == null ||
          checkedNodesAll == undefined ||
          checkedNodesAll == ''
        ) {
          return
        }
        checkedNodesAll.forEach((e) => {
          arr.push({ groupType: 'videogroup', groupID: e.id })
        })
        this.videoTreeCheckedArr = arr
        let group = this.currentItem.group
        let newGroup = group.filter((e) => {
          return e.groupType != 'videogroup'
        })
        newGroup = newGroup.concat(arr)
        this.currentItem.group = deepClone(newGroup)
      } else {
        this.$message.warning('组织树选择状态错误')
        return
      }
    },
    // 添加按钮
    handleAdd() {
      let _this = this
      const len = this.authList.filter((e) => {
        return e.rightGroupID == '99999999'
      }).length
      if (len > 0) {
        return
      }
      this.$refs.authTree.setCheckedKeys([])
      let obj = {
        rightGroupName: this.$i18n.locale == 'en-US' ? '<Add>' : '<新增>',
        isAdmin: 0,
        rightGroupID: '99999999',
        rightID: [],
        editStatus: 'add',
        name: '99999999',
        group: [],
      }
      this.authList.push(obj)
      _this.currentItem = deepClone(obj)
      _this.currentItem.editStatus = 'add'
      _this.currentTabName = '99999999'
      _this.handleClick(obj)
      this.$forceUpdate()
    },
    //新增/修改
    handleCreate() {
      if (this.currentItem.editStatus == 'add') {
        if (this.currentItem.rightID.length == 0) {
          this.$message.warning('请至少选择一个关联模块')
          return
        }
        if (this.modelName == '') {
          this.showTips = true
          this.$refs['modelName'].focus()
          return
        }
        let obj = {
          request: {
            '@id': '10000',
            '@type': 'RightGroupAdd',
            rightGroupName: this.modelName,
            isAdmin: '0',
            rightID: this.currentItem.rightID,
          },
        }
        dataflow(obj).then((res) => {})
      } else if (this.currentItem.editStatus == 'update') {
        let obj = {
          request: {
            '@id': '10000',
            '@type': 'RightGroupMod',
            rightGroupID: this.currentItem.rightGroupID,
            rightGroupName: this.modelName,
            isAdmin: '0',
            rightID: this.currentItem.rightID,
          },
        }
        dataflow(obj).then((res) => {})
      }
    },
    //打开编辑
    handleUpdate() {
      this.currentItem.editStatus = 'update'
      this.currentItem = { ...this.currentItem }
      this.modelName = this.currentItem.rightGroupName
      //当前模块点击，触发渲染
      this.handleGoto(this.titleNum)
      this.$forceUpdate()
    },
    //取消
    handleCancel() {
      this.currentItem.editStatus = 'get'
      this.currentItem = { ...this.currentItem }
      this.$forceUpdate()
    },
    //删除
    handleDel() {
      this.$confirm(this.$t('m.tip.DELECT_TIP'), this.$t('m.tip.TIPS'), {
        confirmButtonText: this.$t('m.CONFIRM'),
        cancelButtonText: this.$t('m.CANCEL'),
        type: 'warning',
      }).then(() => {
        let obj = {
          request: {
            '@id': '10000',
            '@type': 'RightGroupDel',
            rightGroupID: this.currentItem.rightGroupID,
          },
        }
        dataflow(obj).then((res) => {})
      })
    },
    //设置权限组和组的对应关系。
    handleUpdateRelation(rightGroupID) {
      let newGroup = []
      let group = this.currentItem.group
      group.forEach((e) => {
        let groupType = e.groupType == 'dispatchgroup' ? 'organ' : e.groupType
        let str = e.groupID + '|' + groupType + '|1'
        newGroup.push(str)
      })
      let obj = {
        request: {
          '@id': '10000',
          '@type': 'RightGroupSet',
          rightGroupID: rightGroupID,
          isEnd: '1',
          group: newGroup,
        },
      }
      dataflow(obj).then((res) => {
        this.init()
      })
    },
    // 关闭弹出窗
    handleClose() {
      this.$emit('update:authDialog', false)
    },
    // 组过滤
    groupFilter(value, data, node) {
      return data.obj.groupType !== 'dispatchgroup'
    },
    //构建权限组织树
    handleMakeTree(data) {
      //判断语音
      if (this.$i18n.locale == 'en-US') {
        this.authTreeDataShow = toTree(
          data,
          'parentRightID',
          'rightID',
          'rightCode'
        )
      } else {
        this.authTreeDataShow = toTree(
          data,
          'parentRightID',
          'rightID',
          'rightName'
        )
      }
    },
  },
  mounted() {
    this.init()
    SDK.setEventMore(this.eventMore)
    // this.fiterUserGroupTreeData()
  },
}
</script>

<style lang="scss" scoped>
/deep/.auth-dialog {
  width: 900px;
  height: 550px;
  background-color: #1a4969;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .aside {
    color: white;
    margin: 20px;
    text-align: center;
    font-size: 16px;
    .main-part {
      height: 40px;
      line-height: 35px;
      background-color: #125ba7;
    }
    .part {
      height: 40px;
      line-height: 35px;
      background-color: #172a47;
    }
    .part:hover {
      border: 1px solid white;
      border-radius: 10px;
    }
    .checked {
      background-color: #5596da;
      border: 1px solid white;
      border-radius: 10px;
    }
  }
  // 标签页
  .el-tabs--left.el-tabs--card .el-tabs__nav {
    border: none;
  }
  .el-tabs__item {
    color: white !important;
    width: 100%;
    text-align: center !important;
    background-color: #0a182c;
    border-radius: 10px;
  }
  .el-tabs__item:hover {
    cursor: pointer;
  }
  .el-tabs__item.is-active {
    background-color: #6bb5e6 !important;
  }
  .el-tabs--left .el-tabs__header.is-left {
    width: 98%;
  }

  .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
    background-color: #010d1f;
    border-color: #1a1d23;
  }

  ._main {
    color: white;
    height: 85%;
    ._main-header {
      display: flex;
      line-height: 30px;
      margin-top: 5px;
      .header-part {
        width: 200px;
        height: 30px;
        text-align: center;
        border-radius: 10px;
        cursor: pointer;
      }
      .checked {
        background-color: #172a47;
      }
    }
    ._main-body {
      height: 100%;
      margin-top: 5px;
      .el-tree {
        background-color: #172a47;
        color: #fff;
      }
    }
  }
  .el-dialog__close {
    color: #fff;
  }

  .el-dialog__header {
    .el-dialog__title {
      color: #fff;
    }
  }

  .el-input__inner {
    background-color: #1a4969;
    color: #fff;
    height: 30px;
  }
  .el-dialog__body {
    padding: 0;
    height: 480px;
    .inline-input {
      margin-bottom: 10px;
      width: 100%;
      .el-input__inner {
        background-color: #1a4969;
        color: #fff;
      }
      .el-autocomplete-suggestion li {
        color: white;
      }
    }
  }
  .el-dialog__footer {
    background-color: #1a4969;
    padding: 5px 30px;
    height: 45px;
    .el-button {
      width: 70px;
      background-color: #1a4969;
      color: #ffffff;
      &:hover {
        background-color: #409eff;
      }
    }
  }

  .default-scrollbar {
    width: 100%;
    height: calc(100% - 20px);
    background-color: #172a47;
  }

  .default-scrollbar__wrap {
    width: auto;
    overflow-x: hidden;
    margin-right: -20px !important;
  }

  .el-tree-node__content {
    height: 34px;
    cursor: default;

    &:hover {
      background-color: #172a47;
      border: 1px solid #d0cdcd;
      color: white;
    }
  }

  .el-tree-node.is-current > .el-tree-node__content {
    // background-color: #00b2ee;
    // #6BB5E6
    background-color: #6bb5e6;
    //color: #ffffff;
    color: #000;
  }

  .el-container {
    height: 100%;

    .aside-left {
      width: 200px !important;
      height: 100%;
      margin-left: 10px;

      .el-tree {
        background-color: #172a47;
        color: #fff;
      }
    }

    .el-main {
      height: 100%;
      padding-top: 0px;

      .el-table {
        background-color: #1a4969;
        height: 425px;

        td {
          border-bottom: 1px solid #2e67a8;
        }

        tr:hover > td {
          background-color: #2f6b8d;
        }

        .table-herder-custom {
          background-color: #2e67a8;
          color: #fff;
        }

        .table-cell-custom {
          background-color: #172a47;
          color: #fff;

          .el-link {
            color: #fff;
            margin-left: 20px;

            span {
              font-size: 10px;
            }

            &:hover {
              color: #06f7bb;
            }
          }
        }

        .el-table__body tr.current-row > td {
          background: #00b2ee !important;
        }
      }

      .el-table::before {
        height: 0;
      }
    }
  }

  .aside-right {
    height: 425px;
    margin-right: 10px;
    margin-bottom: 20px;
    border: 1px solid #00b2ee;
    border-radius: 5px;
    background-color: #172a47;
  }

  .right-scrollbar {
    width: 100%;
    height: calc(100% - 40px);
  }

  .right-scrollbar__wrap {
    width: auto;
    overflow-x: hidden;
  }

  .input-text {
    height: 36px;
    line-height: 36px;
    display: flex;
    align-items: center;

    .el-input {
      margin-left: 3px;

      .el-input__inner {
        background-color: #172a47;
        color: #fff;
      }
    }

    .el-button {
      height: 28px;
      padding: 0 10px;
      margin: 0 2px;
    }
  }

  .distribution-item {
    border: 1px solid rgba(255, 255, 255, 0.4);
    margin: 3px 2px;
    color: #fff;
    display: flex;

    div {
      width: 50%;
      height: 36px;
      line-height: 36px;
      text-align: center;
    }
  }

  .distribution-item:hover {
    background-color: #a4cedb;
  }

  .distribution-commit {
    text-align: center;
    margin-top: 5px;

    .el-button {
      height: 30px;
      width: 80px;
      background-color: #172a47;
      color: #fff;
      padding: 0;
    }

    .el-button:hover {
      background-color: #409eff;
    }
  }

  @media screen and (max-width: 1024px) {
    width: 800px;
    height: 450px;

    .el-dialog__body {
      height: 400px;
    }

    .aside-left {
      width: 150px !important;
    }

    .el-main {
      padding-right: 5px;
      padding-left: 5px;
    }

    .el-table {
      height: 380px !important;
    }

    .el-tree-node__label {
      font-size: 12px;
    }

    .aside-right {
      height: 380px;
    }

    .distribution-item {
      font-size: 12px;
    }
  }
}
</style>
